package com.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.entity.UserEntity;
import com.service.UserService;
import com.service.serviceImpl.UserServiceImpl;
import utils.ResInfo;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class registerServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private ResInfo resInfo = new ResInfo();
    private Map<String, Object> map = new HashMap<String, Object>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        // 检查验证码
        JSONObject jsonObject = JSON.parseObject(params);
        String check = jsonObject.get("check").toString();
        HttpSession session = request.getSession();
        String code = session.getAttribute("code").toString();
        if (!code.equalsIgnoreCase(check)) {
            map.put("flag", false);
            map.put("msg", "验证码错误");
            String JSONMap = JSON.toJSONString(map);
            response.getWriter().write(JSONMap);
            session.removeAttribute("code");
            return;
        }
        // 查询数据库是否有相同账号
        UserEntity userEntity = JSON.parseObject(params, UserEntity.class);
        UserEntity s1 = userService.UserNamecheckDuplicate(userEntity.getUserName());
        if (s1 != null) {
            map.put("flag", false);
            map.put("msg", "用户名重复");
        } else if (s1 == null) {
            userService.insertUser(userEntity);
            map.put("flag", true);
            map.put("msg", "注册成功");
        } else {
            map.put("msg", "注册失败");
            map.put("flag", false);
        }
        session.removeAttribute("code");
        String JSONMap = JSON.toJSONString(map);
        response.getWriter().write(JSONMap);
    }
}
